<?php
declare (strict_types=1);

namespace app\controller;

use app\facade\Param;
use app\handler\Aes;
use app\helpers\api\ApiResponse;
use app\model\User;
use think\Request;

class UserController
{
    use ApiResponse;

    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index(Request $request)
    {
        $query = User::order('create_time', 'desc');
        $query = Param::userParam($request->param(), $query);
        return $this->success($query->paginate($request->param('page_size', 15)));
    }

    /**
     * 详情
     * @param User $user
     * @return mixed
     */
    public function show(User $user)
    {
        return $this->success($user);
    }

    /**
     * @param Request $request
     * @return mixed
     */
    public function store(Request $request, Aes $aes)
    {
        $validate = new \app\validate\User();
        $res      = $validate->check($request->param());
        if (!$res) {
            return $this->error($validate->getError());
        }
        $data = $request->param();
        if ($request->param('password')) $data['password'] = $aes->encode($request->param('password'));
        User::create($data);
        return $this->created();
    }

    public function save(Request $request, User $user, Aes $aes)
    {
        $data = $request->param();
        if ($request->param('password')) $data['password'] = $aes->encode($request->param('password'));
        $user->update($data);
        return $this->update();
    }

    public function delete(User $user)
    {
        $user->delete();
        return $this->destroy();
    }
}
